from flask import json
from jinja2.tests import test_number
from openpyxl.styles.builtins import total
from peewee import JOIN, fn

from common.public import *
from orm.model import Test, db, TestDetails, QuestionBank, TestPaper
from view.baseview import BaseView
from view.testpaperview import TestPaperView


class TestView(BaseView):
    def __init__(self):
        pass

    @db.atomic() 
    def removeTest(self, params):
        """
        删除考试信息
        """
        test = Test.get(Test.id == params["testId"])
        # test.delete_instance()
        rows = TestPaper.select().where(TestPaper.exam_id == params["testId"])
        # TestPaper.delete().where(TestPaper.exam_id == params["testId"]).execute()
        for row in rows:
            TestDetails.delete().where(TestDetails.test_id == row.id).execute()
        TestPaper.delete().where(TestPaper.exam_id == params["testId"]).execute()
        test.delete_instance()
        return super().resultSet(200, "删除成功", [])
        raise Exception("删除失败")    

    @db.atomic() 
    def startTest(self, params):
        """
        开始考试
        """
        test = Test.get(Test.id == params["testId"])
        print(params)
        test.state = TESTSTATE_ONGOING
        test.save()
       
        return super().resultSet(200, "修改成功", [])
        raise Exception("修改失败")    
    def queryTest(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        result = []
        print(params["type"])
        where_condition = True
        if params["name"]:
            likestr = "%" + params["name"] + "%"
            where_condition = (Test.name ** likestr)
        if params["state"]:
            where_condition = where_condition & (Test.state == params["state"])
        if params["type"]:
            where_condition = where_condition & (Test.type == params["type"])
        if params["stype"]:
            where_condition = where_condition & (Test.stype == params["stype"])
        if params["addTime"]:
            where_condition = where_condition & ((Test.add_time >= params["addTime"][0] + " 00:00:00") \
                                               & (Test.add_time <= params["addTime"][1] + " 23:59:59"))
        if params["updateTime"]:
            where_condition = where_condition & ((Test.update_time >= params["updateTime"][0] + " 00:00:00") \
                                               & (Test.update_time <= params["updateTime"][1] + " 23:59:59"))
       
#
        total = Test.select().where(where_condition).count()
        rows = Test.select().where(where_condition).order_by(Test.add_time.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows:
            if row.add_time != None:
                row.add_time = time.strftime("%Y-%m-%d", time.strptime(str(row.add_time), "%Y-%m-%d %H:%M:%S"))
            if row.update_time != None:
                row.update_time = time.strftime("%Y-%m-%d", time.strptime(str(row.update_time), "%Y-%m-%d %H:%M:%S"))
            if row.end_time != None:
                row.end_time = time.strftime("%Y-%m-%d", time.strptime(str(row.end_time), "%Y-%m-%d %H:%M:%S"))
            r1 = TestPaper.select().where(TestPaper.exam_id == row.id)
            passnumber = 0
            for r in r1:
                if r.score != None:
                    if r.score >= r.pass_mark:
                        passnumber = passnumber + 1
            #第几次考试
            row.pass_number = passnumber
            row.save()
            data = {
                "id":row.id,
                "name":row.name,
                "type":row.type,
                "stype":row.stype,
                "totalNumber":row.total_number,
                "totalScore":row.total_score,
                "examineNumber":row.examine_number,
                "passNumber":row.pass_number,
                "passMark":row.pass_mark,
                "testTotalTimes":row.test_total_times,
                "state":row.state,
                "endTime":row.end_time,
                "addTime":row.add_time,
                "updateTime":row.update_time,
             }
            result.append(data)
        return super().resultSet(200, "", result, total = total)

    @db.atomic() 
    def addTest(self, params):
        print(params)
        """
        新增考试和随机生成试卷
        """ 
        result = []
        where_condition = True
        if params["type"]:
            where_condition = where_condition & (QuestionBank.type == params["type"])
        if params["stype"]:
            where_condition = where_condition & (QuestionBank.stype.in_(params["stype"]))
        total = QuestionBank.select().where(where_condition).count()
        print(total)
        if int(params["totalNumber"]) > total:
            return super().resultSet(500, "题库不够添加失败", result)
        test = Test.create(
            name = params["name"],
            total_number = params["totalNumber"],
            type = params["type"],
            stype = params["stype"],
            end_time = params["endTime"],
            total_score = params["totalScore"],
            examine_number = params["examineNumber"],
            pass_number = params["passNumber"],
            pass_mark = params["passMark"],
            test_total_times = params["testTotalTimes"],
            state = params["state"],
            add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        )
        test.save()
        if params["pName"]:
            for p_name in params["pName"]:
                testpaper = TestPaper.create(
                    identity_card = "000000000000000000",
                    name = p_name,
                    test_number = 1,
                    pass_mark = params["passMark"],
                    test_type = params["type"],
                    question_total = params["totalNumber"],
                    total_score = params["totalScore"],
                    exam_id = test.id,
                    add_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                )
                testpaper.series_id = testpaper.id
                testpaper.save()
                if params["danxuan"]:
                    where_condition1 = where_condition & (QuestionBank.question_type == "单选")
                if params["duoxuan"]:
                    where_condition2 = where_condition & (QuestionBank.question_type == "多选")
                query1 = (QuestionBank.select().where(where_condition1).order_by(fn.Rand()).limit(int(params["danxuan"])))
                query2 = (QuestionBank.select().where(where_condition2).order_by(fn.Rand()).limit(int(params["duoxuan"])))
                rows = (query1 + query2).order_by(fn.Rand())
                for row in rows: 
                    TestDetails.create(
                        test_id = testpaper.id,
                        question_bank_id = row.id
                        )
        return super().resultSet(200, "添加成功", result)
        raise Exception("添加失败")
